package utilities;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {

    // 将字节数组写入文件中，为覆盖写入
    public static void byteToFile(byte[] buf, String filePath, String fileName)
    {

        System.out.println("byte to file");
        FileOutputStream fileOut = null;
        BufferedOutputStream bufferOut = null;
        File file = null;
        try
        {
            File resFile = new File(filePath);
            if (!resFile.exists())
            {
                resFile.mkdirs();
                System.out.println("directories made");
            }
            System.out.println(resFile.getCanonicalPath());
            file = new File(filePath + File.separator + fileName);
            if(!file.exists())
            {
                file.createNewFile();
                System.out.println("file created");
            }
            System.out.println(file.getCanonicalPath());
            fileOut = new FileOutputStream(file);
            bufferOut = new BufferedOutputStream(fileOut);
            bufferOut.write(buf);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (bufferOut != null)
            {
                try
                {
                    bufferOut.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (fileOut != null)
            {
                try
                {
                    fileOut.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

    }
}
